﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using LuaInterface;

namespace PuyoNeuron
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        public delegate void ClickAction(Vector2 pLocation);

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        List<Panel> mPanels;
        MouseState mPreviousMouseState;
        IUIElement mMouseOver;
        ContextMenu mContextMenu;
        Vector2? mDraggingCameraBy;
        Vector2? mDragBoxStart;
        Texture2D mDragBoxTexture;
        Dictionary<string, string> mPanelSources;

        // there should only be one text editor open at a time... is this a cheap fix? not sure...
        static TextEditor sTextEditor;
        static KeyboardBuffer sKeyBuffer;

        public static TextEditor TextEditor
        {
            get { return sTextEditor; }
            set { sTextEditor = value; }
        }

        public static KeyboardBuffer KeyBuffer
        {
            get { return sKeyBuffer; }
            set { sKeyBuffer = value; }
        }
        
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            sKeyBuffer = new KeyboardBuffer(Window.Handle);
            sKeyBuffer.TranslateMessage = true;
            sKeyBuffer.Enabled = true;
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            mPanels = new List<Panel>();

            IsMouseVisible = true;

            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 768;
            graphics.ApplyChanges();

            Camera.Instance.Center = new Vector2(0, 0);

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            mPreviousMouseState = Mouse.GetState();

            Panel.PanelTexture = Content.Load<Texture2D>("panel");
            Panel.NubTexture = Content.Load<Texture2D>("nub");
            Panel.DotTexture = Content.Load<Texture2D>("dot");
            Panel.TitleFont = Content.Load<SpriteFont>("title");
            Panel.LabelFont = Content.Load<SpriteFont>("label");
            ContextMenu.MenuTexture = Content.Load<Texture2D>("context");
            ContextMenu.HilightTexture = Content.Load<Texture2D>("hilight");
            ContextMenu.LabelFont = Content.Load<SpriteFont>("label");
            Constant.ConstantTexture = Content.Load<Texture2D>("constant");
            mDragBoxTexture = Content.Load<Texture2D>("select");
            TextEditor.TextEditorTexture = Content.Load<Texture2D>("input");
            TextEditor.CursorTexture = Content.Load<Texture2D>("cursor");

            // load lua and run a quick test
            Lua lua = new Lua();

            ///////////// trying to figure out how to get unicode into lua //////////////////

            //string lString = "return \"おちんこです\"";
            //System.Diagnostics.Debug.WriteLine(lString);
            //string lAscii = Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(lString));
            //string lUTF8 = Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(lString));

            //System.Diagnostics.Debug.WriteLine(lAscii.Length);

            //string lReturn = lua.DoString(lAscii)[0].ToString();
            //string lUnicode = Encoding.Default.GetString(Encoding.ASCII.GetBytes(lReturn));
            //System.Diagnostics.Debug.WriteLine(lUnicode);

            ///////////// it's not very effective ///////////////////////////////////////////

            lua.RegisterFunction("puts", this, GetType().GetMethod("Lua_Puts"));
            lua.DoString("puts(\"lua working\")");


            // build a dictionary of all .lua's we know about
            mPanelSources = new Dictionary<string, string>();
            string[] lPanelSources = Directory.GetFiles("lua");
            foreach (string lPanelSource in lPanelSources)
            {
                if (lPanelSource.EndsWith("start.lua") || lPanelSource.EndsWith("constant.lua"))
                    continue;

                TextReader lPanelSourceFile = new StreamReader(lPanelSource);
                string lLine;

                // keep reading until we find a "-- :name" line then save it as lLine
                while (!(lLine = lPanelSourceFile.ReadLine() ?? "").StartsWith("-- :name"))
                    ;

                string lName = lLine.Split('=')[1].Trim();

                mPanelSources[lName] = lPanelSource;

                lPanelSourceFile.Close();
            }
        }

        public void Lua_Puts(object pStr)
        {
            if (pStr == null)
                System.Diagnostics.Debug.WriteLine("null");
            else
                System.Diagnostics.Debug.WriteLine(pStr.ToString());
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            Panel lMoveToTop = null;

            MouseState lMouseState = Mouse.GetState();
            IUIElement lOverPanel = GetUIElementAt(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)));

            Camera.Instance.Zoom = lMouseState.ScrollWheelValue / 1200f + 1f;
            if (mDraggingCameraBy.HasValue)
            {
                Camera.Instance.Center += (mDraggingCameraBy.Value - new Vector2(lMouseState.X, lMouseState.Y)) / Camera.Instance.Zoom;
                mDraggingCameraBy = new Vector2(lMouseState.X, lMouseState.Y);
            }

            foreach (Panel lPanel in mPanels)
            {
                lPanel.Update();
            }

            if (sTextEditor != null)
                sTextEditor.Update();

            // left mouse button down
            if (lMouseState.LeftButton == ButtonState.Pressed && mPreviousMouseState.LeftButton == ButtonState.Released)
            {
                if (lOverPanel != null)
                {
                    lOverPanel.OnClick(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)) - lOverPanel.TopLeft);
                    if (lOverPanel is Panel)
                        lMoveToTop = (Panel)lOverPanel;
                }
                else
                {
                    mDragBoxStart = new Vector2(lMouseState.X, lMouseState.Y);
                }

                foreach (Panel lPanel in mPanels)
                    lPanel.OnMouseDown(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)) - lPanel.TopLeft);
                
                if (lOverPanel != mContextMenu)
                    mContextMenu = null;
            }

            // left mouse button up
            if (lMouseState.LeftButton == ButtonState.Released && mPreviousMouseState.LeftButton == ButtonState.Pressed)
            {
                if (lOverPanel != null)
                    lOverPanel.OnRelease(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)) - lOverPanel.TopLeft);

                mDraggingCameraBy = null;
                mDragBoxStart = null;

                foreach (Panel lPanel in mPanels)
                    lPanel.OnMouseUp(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)) - lPanel.TopLeft);
            }

            if (lOverPanel != mMouseOver)
            {
                if (mMouseOver != null)
                    mMouseOver.OnExit();

                if (lOverPanel != null)
                    lOverPanel.OnEnter();

                mMouseOver = lOverPanel;
            }

            if (lMoveToTop != null)
            {
                mPanels.Remove(lMoveToTop);
                mPanels.Add(lMoveToTop);
            }

            // right mouse button up
            if (lMouseState.RightButton == ButtonState.Released && mPreviousMouseState.RightButton == ButtonState.Pressed)
            {
                if (sTextEditor != null)
                {
                    // TODO: context menus for inside text editor
                }
                else if (lOverPanel != null && lOverPanel is Panel)
                {
                    mContextMenu = ((Panel)lOverPanel).GetContextMenuFor(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)) - lOverPanel.TopLeft);
                }
                else
                {
                    mContextMenu = new ContextMenu(Camera.Instance.ToWorld(new Vector2(lMouseState.X, lMouseState.Y)));

                    mContextMenu.Items.Add(new ContextMenu.ContextItem("constant", pLocation => AddConstantPanel(pLocation)));

                    mContextMenu.Items.Add(new ContextMenu.ContextItem("start",
                                                                       delegate(Vector2 pLocation)
                                                                           {
                                                                               CodeModel.Instance.Start.Add(
                                                                                   AddPanel("lua/start.lua", pLocation).Title + ".fire");
                                                                           }));

                    foreach (KeyValuePair<string, string> lPanelSource in mPanelSources)
                    {
                        string lPath = lPanelSource.Value;
                        mContextMenu.Items.Add(new ContextMenu.ContextItem(lPanelSource.Key, pLocation => AddPanel(lPath, pLocation)));
                    }

                    mContextMenu.Items.Add(new ContextMenu.ContextItem("---", null));
                    mContextMenu.Items.Add(new ContextMenu.ContextItem("run",
                                    delegate
                                        {
                                            string lCompiled = CodeModel.Instance.Compile();
                                            string lLineNumbers = "";
                                            for (int i = 0; i < lCompiled.Split('\n').Count(); i++)
                                                lLineNumbers += //(i + 1).ToString("000") + ":  " +
                                                                lCompiled.Split('\n')[i] + "\n";

                                            System.Diagnostics.Debug.WriteLine("-- ===== COMPILED LUA CODE ===== --\n"
                                                                               + lLineNumbers
                                                                               + "\n-- === END COMPILED LUA CODE === --");
                                            Lua lLua = new Lua();
                                            lLua.RegisterFunction("puts",
                                                                  this,
                                                                  GetType().GetMethod("Lua_Puts"));
                                            try
                                            {
                                                lLua.DoString(lCompiled);
                                            }
                                            catch (Exception e)
                                            {
                                                System.Diagnostics.Debug.WriteLine(e.Message);
                                            }
                                        }));
                }
            }

            // middle mouse button down
            if (lMouseState.MiddleButton == ButtonState.Pressed && mPreviousMouseState.MiddleButton == ButtonState.Released)
            {
                mDraggingCameraBy = new Vector2(lMouseState.X, lMouseState.Y);
            }

            // middle mouse button up
            if (lMouseState.MiddleButton == ButtonState.Released && mPreviousMouseState.MiddleButton == ButtonState.Pressed)
            {
                mDraggingCameraBy = null;
            }

            mPreviousMouseState = lMouseState;
            
            // remove panels and menus that have been marked for disposal
            if (mContextMenu != null && mContextMenu.Dispose)
                mContextMenu = null;

            if (sTextEditor != null && sTextEditor.Dispose)
                sTextEditor = null;

            List<Panel> lRemove = new List<Panel>();
            foreach (Panel lPanel in mPanels.Where(delegate(Panel pPanel) { return pPanel.Dispose; }))
                lRemove.Add(lPanel);
            foreach (Panel lPanel in lRemove)
                RemovePanel(lPanel);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(new Color(.2f, .3f, .4f));

            spriteBatch.Begin();

            foreach (Panel lPanel in mPanels)
                lPanel.Draw(spriteBatch);

            if (mContextMenu != null)
                mContextMenu.Draw(spriteBatch);
            
            if (mDragBoxStart.HasValue)
            {
                spriteBatch.Draw(mDragBoxTexture,
                                 mDragBoxStart.Value,
                                 new Rectangle(0, 0, 32, 32),
                                 Color.White, 0f, Vector2.Zero,
                                 (new Vector2(Mouse.GetState().X, Mouse.GetState().Y) - mDragBoxStart.Value) / 32f,
                                 SpriteEffects.None, 0f);
            }

            if (sTextEditor != null)
                sTextEditor.Draw(spriteBatch);

            spriteBatch.End();

            base.Draw(gameTime);
        }

        public Panel AddPanel(string pFileName, Vector2 pLocation)
        {
            Panel lPanel = new Panel(pFileName, pLocation);
            mPanels.Add(lPanel);
            CodeModel.Instance.Add(lPanel);
            return lPanel;
        }

        public Panel AddConstantPanel(Vector2 pLocation)
        {
            Constant lConstant = new Constant(pLocation);
            mPanels.Add(lConstant);
            CodeModel.Instance.Add(lConstant);
            return lConstant;
        }

        public void RemovePanel(Panel lPanel)
        {
            foreach (Panel.Nub lNub in lPanel.Nubs)
                lNub.BreakAll();
            
            mPanels.Remove(lPanel);
            CodeModel.Instance.Remove(lPanel);
        }

        private IUIElement GetUIElementAt(Vector2 pLocation)
        {
            // text editor grabs entire screen worth of focus. u_u
            if (sTextEditor != null)
                return sTextEditor;

            if (mContextMenu != null &&
                    pLocation.X >= mContextMenu.TopLeft.X - 4 &&
                    pLocation.X <= mContextMenu.TopLeft.X + mContextMenu.Size.X + 4 &&
                    pLocation.Y >= mContextMenu.TopLeft.Y &&
                    pLocation.Y <= mContextMenu.TopLeft.Y + mContextMenu.Size.Y)
            {
                return mContextMenu;
            }

            mPanels.Reverse(); // reverse order of panels so we encounter top panel first when checking

            foreach (Panel lPanel in mPanels)
            {
                if (pLocation.X >= lPanel.TopLeft.X - 4 &&
                    pLocation.X <= lPanel.TopLeft.X + lPanel.Size.X + 4 &&
                    pLocation.Y >= lPanel.TopLeft.Y &&
                    pLocation.Y <= lPanel.TopLeft.Y + lPanel.Size.Y)
                {
                    mPanels.Reverse(); // reset panels before returning
                    return lPanel;
                }
            }

            mPanels.Reverse(); // reset panels before returning
            return null;
        }
    }
}